package com.ai.bitcoin.schedule.task;

import com.ai.bitcoin.jpa.entity.BccRank;
import com.ai.bitcoin.jpa.entity.BccShowControl;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;

import java.lang.reflect.Field;
import java.util.List;

/**
 * @author Jason
 * @date 2018/4/3
 **/
@Slf4j
public abstract class AbstractTask implements ICrontask {

    @Value("${pageSizeHome}")
    int pageSizeHome;
    @Value("${pageSizeDb}")
    int pageSizeDb;

    String getBtcId() {
        return "1";
    }

    void setField(BccRank bccRank, String scoreType, Object score) {
        try {
            Field f = bccRank.getClass().getDeclaredField(scoreType);
            f.setAccessible(true);
            f.set(bccRank, score);
            f.set(bccRank, score);
        } catch (IllegalAccessException | NoSuchFieldException e) {
            log.warn(e.getMessage(), e);
        }
    }

    Object getField(Object bean, String field) {
        try {
            Field f = bean.getClass().getDeclaredField(field);
            f.setAccessible(true);
            return f.get(bean);
        } catch (NoSuchFieldException | IllegalAccessException e) {
            log.info(e.getMessage(), e);
        }
        return null;
    }


    JSONObject getShowInfo(JSONObject info, BccShowControl bccShowControl) {
        JSONObject showInfo;
        if (bccShowControl != null) {
            showInfo = new JSONObject();
            JSONArray showFields = JSONArray.fromObject(bccShowControl.getFields());
            for (int i = 0; i < showFields.size(); i++) {
                String key = showFields.getString(i);
                if (StringUtils.isNotEmpty(info.optString(key))) {
                    showInfo.put(key, info.optString(key));
                }
            }
        } else {
            showInfo = info;
        }
        return showInfo;
    }

    private float getSplitAverage(List list) {
        if (list.size() == 0)
            return getDefaultScore();
        float sum = 0;
        int count = 0;
        for (Object aList : list) {
            float value = Float.parseFloat(String.valueOf(aList));
            sum += value;
            count++;
        }
        return sum / count;
    }

    float getDefaultScore() {
        return 0;
    }

    int getDefaultRank() {
        return 0;
    }

}


